package estore.src.estore.view;
import estore.src.estore.model.Product;
import estore.src.estore.service.ProductService;
import java.util.List;
import java.util.Scanner;
import java.io.*;

/**
 * 控制台商店界面
 */
public class ConsoleShop {
    private ProductService productService;
    private Scanner scanner;

    public ConsoleShop() {
        productService = new ProductService();
        scanner = new Scanner(System.in);
    }

    public void start() {
        System.out.println("=== 欢迎使用电子商店管理系统 ===");

        while (true) {
            showMenu();
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    addProduct();
                    break;
                case "2":
                    showAllProducts();
                    break;
                case "3":
                    searchProduct();
                    break;
                case "4":
                    updateProduct();
                    break;
                case "5":
                    deleteProduct();
                    break;
                case "6":
                    updateStock();
                    break;
                case "99": // 隐藏的管理员功能 - 数据备份
                    backupData();
                    break;
                case "0":
                    System.out.println("正在保存数据...");
                    productService.saveData();
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void showMenu() {
        System.out.println("\n请选择操作：");
        System.out.println("1. 添加商品");
        System.out.println("2. 显示所有商品");
        System.out.println("3. 搜索商品");
        System.out.println("4. 更新商品信息");
        System.out.println("5. 删除商品");
        System.out.println("6. 更新库存");
        System.out.println("0. 退出系统");
        System.out.print("请输入选择: ");
    }

    /**
     * 备份数据文件
     */
    private void backupData() {
        System.out.println("\n=== 数据备份 ===");

        String sourceFile = "products.dat";
        String backupFile = "products.dat.bak";

        File source = new File(sourceFile);
        if (!source.exists()) {
            System.out.println("源数据文件不存在，无法备份！");
            return;
        }

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(backupFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            System.out.println("数据备份成功！备份文件: " + backupFile);
            System.out.println("文件大小: " + source.length() + " 字节");

        } catch (IOException e) {
            System.err.println("备份失败: " + e.getMessage());
        }
    }

    // 其他方法保持不变...
    private void addProduct() {
        System.out.println("\n=== 添加商品 ===");

        try {
            System.out.print("请输入商品ID: ");
            String id = scanner.nextLine();

            System.out.print("请输入商品名称: ");
            String name = scanner.nextLine();

            System.out.print("请输入商品价格: ");
            double price = Double.parseDouble(scanner.nextLine());

            System.out.print("请输入商品库存: ");
            int stock = Integer.parseInt(scanner.nextLine());

            Product product = new Product(id, name, price, stock);

            if (productService.addProduct(product)) {
                System.out.println("商品添加成功！");
            } else {
                System.out.println("商品添加失败，ID已存在！");
            }

        } catch (NumberFormatException e) {
            System.out.println("输入格式错误，请确保价格和库存为有效数字！");
        } catch (IllegalArgumentException e) {
            System.out.println("输入错误: " + e.getMessage());
        }
    }

    private void showAllProducts() {
        System.out.println("\n=== 所有商品列表 ===");
        List<Product> products = productService.getAllProducts();

        if (products.isEmpty()) {
            System.out.println("暂无商品信息。");
        } else {
            for (Product product : products) {
                System.out.println(product);
            }
            System.out.println("总计: " + products.size() + " 个商品");
        }
    }

    private void searchProduct() {
        System.out.println("\n=== 搜索商品 ===");
        System.out.print("请输入商品名称关键字: ");
        String keyword = scanner.nextLine();

        List<Product> results = productService.searchProductsByName(keyword);

        if (results.isEmpty()) {
            System.out.println("未找到匹配的商品。");
        } else {
            System.out.println("找到 " + results.size() + " 个匹配的商品:");
            for (Product product : results) {
                System.out.println(product);
            }
        }
    }

    private void updateProduct() {
        System.out.println("\n=== 更新商品信息 ===");
        System.out.print("请输入要更新的商品ID: ");
        String id = scanner.nextLine();

        Product existingProduct = productService.findProductById(id);
        if (existingProduct == null) {
            System.out.println("商品不存在！");
            return;
        }

        System.out.println("当前商品信息: " + existingProduct);

        try {
            System.out.print("请输入新商品名称 (直接回车保持原值): ");
            String newName = scanner.nextLine();
            if (!newName.trim().isEmpty()) {
                existingProduct.setName(newName);
            }

            System.out.print("请输入新价格 (直接回车保持原值): ");
            String priceInput = scanner.nextLine();
            if (!priceInput.trim().isEmpty()) {
                existingProduct.setPrice(Double.parseDouble(priceInput));
            }

            System.out.print("请输入新库存 (直接回车保持原值): ");
            String stockInput = scanner.nextLine();
            if (!stockInput.trim().isEmpty()) {
                existingProduct.setStock(Integer.parseInt(stockInput));
            }

            if (productService.updateProduct(existingProduct)) {
                System.out.println("商品信息更新成功！");
            } else {
                System.out.println("商品信息更新失败！");
            }

        } catch (NumberFormatException e) {
            System.out.println("输入格式错误！");
        } catch (IllegalArgumentException e) {
            System.out.println("输入错误: " + e.getMessage());
        }
    }

    private void deleteProduct() {
        System.out.println("\n=== 删除商品 ===");
        System.out.print("请输入要删除的商品ID: ");
        String id = scanner.nextLine();

        if (productService.removeProduct(id)) {
            System.out.println("商品删除成功！");
        } else {
            System.out.println("商品删除失败，ID不存在！");
        }
    }

    private void updateStock() {
        System.out.println("\n=== 更新库存 ===");
        System.out.print("请输入商品ID: ");
        String id = scanner.nextLine();

        Product product = productService.findProductById(id);
        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }

        System.out.println("当前库存: " + product.getStock());

        try {
            System.out.print("请输入新库存: ");
            int newStock = Integer.parseInt(scanner.nextLine());

            if (productService.updateStock(id, newStock)) {
                System.out.println("库存更新成功！");
            } else {
                System.out.println("库存更新失败！");
            }

        } catch (NumberFormatException e) {
            System.out.println("输入格式错误，请输入有效数字！");
        }
    }

    public static void main(String[] args) {
        ConsoleShop shop = new ConsoleShop();
        shop.start();
    }
}